package sw.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sw.entity.Result;
import sw.model.MResult;
import sw.model.MWeakness;

@Controller
@RequestMapping("/res")
public class ResultAnalysis extends BaseController {

	public ResultAnalysis(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}
	
	@RequestMapping(value = "/calRisk")
	public String calculate(Integer projectId,String groupIds,  Integer currMenuId,Float acceptStandard){
		 Map<String, List<MResult>> result = riskCalService.calculate(projectId,acceptStandard);
		return "redirect:/pro/pageLink/" +projectId+"/"+groupIds+"/"+currMenuId ;
	}
	
	@RequestMapping(value = "/showResult")
	@ResponseBody
	public Map<String, List<MResult>> showResult(Integer projectId){
		 Map<String, List<MResult>> result = riskCalService.showResult(projectId);
		return result;
	}
	
	@RequestMapping("/exportWord")
    public void downloadModel(HttpServletRequest request, HttpServletResponse response,Integer projectId,String img1,String img2) throws Exception {
		
		String str = Paths.get(UPLOADPATH,"/评估报告.doc").toString();
		riskCalService.exportWord(projectId,str,img1,img2);
        File file = new File(str);
        String filenames = file.getName();
        InputStream inputStream;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            response.reset();
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filenames.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            response.flushBuffer();  
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            os.write(buffer);// 输出文件
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
